package com.lanxin.qx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lanxin.qx.entity.QxRoleFunction;
import com.lanxin.qx.mapper.QxRoleFunctionMapper;
import com.lanxin.qx.service.IQxRoleFunctionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-19
 */
@Service
public class QxRoleFunctionServiceImpl extends ServiceImpl<QxRoleFunctionMapper, QxRoleFunction> implements IQxRoleFunctionService {

    @Autowired
    private QxRoleFunctionMapper roleFunctionMapper;

    //根据角色id拿到角色拥有的所有方法
    @Override
    public List<Integer> getFunctionsByRoleId(Integer roleId) {
        return roleFunctionMapper.getFunctionsByRoleId(roleId);
    }

    @Transactional  // 保证删除和新增的原子性
    @Override
    public boolean saveRolePermissions(Integer roleId, List<Integer> functionIds) {
        // 1.删除该角色原有的所有权限关联
        QueryWrapper<QxRoleFunction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleid", roleId);
        this.remove(queryWrapper);

        // 2.如果无新权限，直接返回成功
        if (functionIds == null || functionIds.isEmpty()) {
            return true;
        }

        // 3.批量插入新的权限关联
        List<QxRoleFunction> roleFunctions = new ArrayList<>();
        for (Integer funcId : functionIds) {
            QxRoleFunction rf = new QxRoleFunction();
            rf.setRoleid(roleId);
            rf.setFunctionid(funcId);
            roleFunctions.add(rf);
        }
        return this.saveBatch(roleFunctions);
    }

}
